<template>
  <!-- aa -->
  <div style="background-color: #ffffff">
    <el-card v-loading="loading">
      <!-- <el-row v-if="content" style="margin-left: 40px">
        <el-button type="success" v-if="userStatus == 0 && userStepId == 0" @click="handleReloadTable">重载数据</el-button>
        <el-button type="success" @click="saveData(false)">保存</el-button>
        <el-button type="success" @click="submitData" v-if="userStatus == 0 && userStepId == 2">审核完成</el-button>
        <el-button type="success" @click="returnWrite" v-if="userStatus == 0 && userStepId > 0">
          退回给填报员
        </el-button>
        <el-button type="success" v-if="userStatus != 0 || userStepId != 0" @click="showRecord">流程记录</el-button>
        <el-button type="success" @click="printDateForm">打印</el-button>
      </el-row> -->
      <el-scrollbar
        :height="textHeight"
        ref="textScrollbarRef"
        style="padding-right: 10px"
      >
        <div
          v-html="content"
          id="dataForm"
          @contextmenu.prevent="openMenu($event)"
          @click="tdColor($event)"
          @dblclick="trColor($event)"
        ></div>
      </el-scrollbar>
    </el-card>
    <!-- 流程记录 -->
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      v-model="recordOpen"
      :title="recordTitle"
      width="950"
    >
      <el-table :data="recordList" v-loading="loadingRecord" max-height="60vh">
        <el-table-column label="步骤" align="center">
          <template #default="scope">
            <span v-if="scope.row.userStepId == 0">填报</span>
            <span v-if="scope.row.userStepId == 1">复核</span>
            <span v-if="scope.row.userStepId == 2">审核</span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="nickName" align="center" />
        <el-table-column label="开始时间" prop="createTime" align="center" />
        <el-table-column label="结束时间" prop="finishTime" />
        <el-table-column label="状态">
          <template #default="scope">
            <span v-if="scope.row.userStatus == 0">未完成</span>
            <span v-if="scope.row.userStatus == 1">已完成</span>
            <span v-if="scope.row.userStatus == 2">退回</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="recordOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <ul
      v-show="visible"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="addTr(contextmenuVal)" v-if="showTr(contextmenuVal)">
        <Plus style="width: 1em; height: 1em" /> 增加行
      </li>
      <li
        @click="delTr(contextmenuVal)"
        v-if="showTr(contextmenuVal)"
        :style="'cursor:' + cursorStyle"
      >
        <Minus style="width: 1em; height: 1em" /> 删除行
      </li>
      <li @click="downWrite(contextmenuVal)" v-if="showDown(contextmenuVal)">
        <Bottom style="width: 1em; height: 1em" /> 向下填充
      </li>
      <li
        v-for="item in childComponentList"
        @click="byConditionDownWrite(contextmenuVal, item.componentId)"
        v-if="showDown(contextmenuVal)"
      >
        <Bottom style="width: 1em; height: 1em" /> 根据{{ item.componentName }}向下填充
      </li>
    </ul>
    <el-button
      @click="upClick"
      style="position: absolute; bottom: 40px; right: 40px; z-index: 9999"
      type="success"
      link
    >
    </el-button>
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="submitOpen"
      :title="submitTitle"
      width="700px"
      @close="submitClose"
    >
      <el-row justify="center">
        <el-col :span="4" style="padding-left: 10px; padding-top: 10px">
          <el-steps direction="vertical" :active="userStepId + 1">
            <el-step title="填报" />
            <el-step title="复核" />
            <el-step title="审核" />
          </el-steps>
        </el-col>
        <el-col :span="20" class="dialogUser">
          <el-input
            style="margin-bottom: 10px"
            v-model="filterText"
            clearable
            placeholder="请输入人员名称"
            prefix-icon="UserFilled"
          >
          </el-input>
          <el-scrollbar height="50vh" ref="scrollbarRef">
            <el-tree
              :data="treeData"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="nodeClick"
              node-key="userId"
              :highlight-current="true"
              ref="treeRef"
              v-loading="treeLoading"
              :filter-node-method="filterNode"
            />
          </el-scrollbar>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitConfirm">确认</el-button>
          <el-button type="danger" @click="submitOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { postContent, getMarkList, delContent } from "@/api/cyCheck/filling";
import {
  getTemplateData,
  addTableData,
  returnWriteData,
  reloadTable,
  userRecordList,
  approveData,
  updateFormSign,
} from "@/api/myTask/myTask";
import { getTreeList } from "@/api/system/newUser";
import { getRealValue, getFormulaResult, isCheckLimitValue } from "@/utils/formula";
import {
  eventLine,
  registerEvent,
  resetData,
  setIsHg,
  eventBzwzIsHg,
  handleSubAndSup,
  getRowspanValue,
} from "@/utils/lims";

import { listFormula, queryQcList } from "@/api/lab/labMethod";

import bus from "@/utils/eventBus";

import "jquery-ui-dist/jquery-ui";
import "jquery-ui-dist/jquery-ui.min.css";
import "@/components//popover/jquery.webui-popover.min.js";
import "@/components/popover/jquery.webui-popover.min.css";
import "@/plugins/jquery.jqprint-0.3.js";
import "@/components/datepicker/datepicker.css?t=1";
import "@/components/datepicker/moment.min.js";
import "@/components/datepicker/datepicker.all.js";
import { nextTick, watch } from "vue";

const { proxy } = getCurrentInstance();

const content = ref("");
const tFId = ref("");
const loading = ref(false);
//用户状态 0：待办 1已办
const userStatus = ref(1);
//步骤id
const userStepId = ref(0);
const tableConfig = ref({});
const tableId = ref(0);
const methodId = ref(0);
const recordOpen = ref(false);
const recordTitle = ref("流程记录");
const recordList = ref([]);
const loadingRecord = ref(false);
const formulaList = ref([]);
const resultFormula = ref();
const nextUser = ref({});

let isWrite = false;
let myId;
let $form;
const props = defineProps({
  tFId: {
    type: String,
  },
  userParams: {
    type: Object,
  },
  tableConfig: {
    type: Object,
  },
  formulaParams: {
    type: Object,
  },
});

watch(
  () => props.tFId,
  (val) => {
    resetData();
    tFId.value = props.tFId;
    bus.off("submit" + tFId.value);
    bus.on("submit" + tFId.value, (item) => {
      debugger;
      if(item.isAutoSave == 'empty_instrument'){
        showTable();
        return;
      }
      saveData(item.isAutoSave)
        .then(() => {
          if (item.isShowTable) showTable();
          if (item.isReport) {
            bus.emit("yqdr");
          }
        })
        .catch((err) => {});
    });
    bus.off("submitCallback");
    bus.on("submitCallback", (callback) => {
      if (!tableId.value || tableConfig.value.isRead == 1) {
        if (callback.bs == 2) {
          callback.method(callback.bs);
          return;
        }
        proxy.$modal.confirm("确认要提交吗？").then(function () {
          callback.method(callback.bs);
        });
        return;
      }
      saveData(true, true)
        .then((res) => {
          if (callback.bs == 2) {
            callback.method(callback.bs);
            return;
          }
          proxy.$modal.confirm("确认要提交吗？").then(function () {
            callback.method(callback.bs);
          });
        })
        .catch((err) => {});
    });
    bus.off("saveCallback");
    bus.on("saveCallback", (callback) => {
      saveData(true, false)
        .then((res) => {
          callback.method();
          return;
        })
        .catch((err) => {});
    });
    bus.on("handleReloadTable" + tFId.value, () => {
      handleReloadTable();
    });

    bus.on("submitData" + tFId.value, (params) => {
      if (params.bs == 1) {
        submitData(params);
        return;
      }
      Manual();
    });
    if (props.userParams) {
      methodId.value = props.userParams.methodId;
    }
    debugger;
    if (props.tableConfig) {
      tableConfig.value = props.tableConfig;
      userStatus.value = tableConfig.value.userStatus;
      userStepId.value = tableConfig.value.userStepId;
      if (
        props.userParams &&
        props.userParams.nextUser &&
        props.userParams.nextUser.nextUserId
      ) {
        nextUser.value.nextUserId = props.userParams.nextUser.nextUserId;
        nextUser.value.nextUserName = props.userParams.nextUser.nextUserName;
      }
      myId = tableConfig.value.myId;
      isWrite =
        userStatus.value == 0 &&
        (userStepId.value == 0 || userStepId.value == 3) &&
        tableConfig.value.isRead != 1;
      tableId.value = tableConfig.value.tableId;
    }
    showTable();
    getFormulaList();
  }
);

function getFormulaList() {
  if (!isWrite) return;
  formulaList.value = [];
  if (tableConfig.value.isRead == 1) return;
  if (!props.formulaParams || !props.formulaParams.tableId) return;
  debugger;
  listFormula(props.formulaParams).then((res) => {
    formulaList.value = res.data;
    bus.emit(
      "getFormulaList",
      res.data.filter((item) => item.isResult == 0)
    );
  });
}

function showTable() {
  if (!tableId.value) {
    content.value = "暂无数据";
    return;
  }
  if (tFId.value) {
    loading.value = true;
    const params = { tFId: tFId.value, userStatus: userStatus.value };
    getTemplateData(params).then((res) => {
      content.value = res.data.content;
      childComponentList.value = res.data.childComponentList;
      if (typeof res.data.isResult == "number") {
        tableConfig.value.isResult = res.data.isResult;
      }
      loading.value = false;
      nextTick(() => {
        $form = $("#dataForm");
        $form.find('td[name="1696048841341812737"]').attr("contenteditable", "false");
        $form.find("td").removeAttr("nowrap");
        if (isWrite) {
          if (tableConfig.value.modelType == 3) {
            bus.emit("handleByTable");
          } else {
            registerEvent(proxy, $form, tableConfig.value);
          }
          $(".datepicker_mm").datePicker({
            format: "YYYY-MM-DD HH:mm",
          });
          $(".datepicker").datePicker({
            format: "YYYY-MM-DD",
          });
          $(".datepicker1").datePicker({
            format: "YYYY年MM月DD日",
          });
          handleQcList();
        }
        if (userStatus.value == 0) {
          registerSign();
        }
        if (userStatus.value == 0) {
          initPopover();
        }
        setFixerTr();
        if ($("tr.childTr").length == 1) {
          cursorStyle.value = "not-allowed";
        } else {
          cursorStyle.value = "pointer";
        }
        handleSubAndSup($form, proxy);
      });
      getHeight();
    });
  }
}

function handleQcList() {
  let modelType = tableConfig.value.modelType;
  if (!methodId.value || !modelType) return;
  let $childTrs = $form.find("tr.childTr");
  let $childTr = $($childTrs[0]);
  if (
    $childTr.length == 0 ||
    !$childTr.attr("sampletype") ||
    $childTr.find("td[name='1733824627435909122']").length == 0
  )
    return;
  queryQcList(methodId.value).then((res) => {
    let qcList = res.data;
    if (qcList.length == 0 && tableConfig.value.modelType != 12) return;
    $childTrs.each(function () {
      let $fw = $(this).find("td[name='1733824627435909122']");
      if (tableConfig.value.modelType == 12) {
        $fw.html("ND");
        if ($(this).find("td[name='1733396715532464136']").text() != "ND") {
          $(this).find("select[name='1733398490884878338']").val("1");
        } else {
          $(this).find("select[name='1733398490884878338']").val("0");
        }
        return true;
      }
      let sampleType = parseInt($(this).attr("sampletype"));
      if (sampleType == 14 || sampleType == 17) {
        sampleType = 0;
      }
      qcList.filter((item) => {
        if (item.qcTypeId == sampleType) {
          if (sampleType == 0 || sampleType == 4 || sampleType == 7) {
            $fw.html(item.pwScope);
          } else {
            if (tableConfig.value.modelType == 12) {
              $fw.html("ND");
            } else if (item.valueScope) $fw.html(item.valueScope);
          }
          return false;
        }
      });
    });
  });
}
function registerSign() {
  let signData = { tFId: tFId.value };
  $(".signBtn").on("click", function () {
    let $signImage = $(this).parent().find("img.sign");
    if ($signImage.length == 0) return;
    let name = $signImage.attr("name");
    let imageData = $signImage.attr("src");
    if (!imageData) return;
    signData.signId = name;
    signData.signStr = imageData;
    updateFormSign(signData).then((res) => {});
  });
}
//设置固定行为表头或表尾
function setFixerTr() {
  let $fixedHead = $("tr.fixed-head");
  let height = 0;
  $fixedHead.each(function (i) {
    $(this).css("top", height + "px");
    height += $(this).height();
  });
  let $fixedFoot = $("tr.fixed-foot");
  height = 0;
  for (let i = $fixedFoot.length - 1; i >= 0; i--) {
    let $this = $fixedFoot.eq(i);
    $this.css("bottom", height + "px");
    height += $this.height() + 1;
  }
}
function getData(isValidate) {
  let jsonData = {};
  if (!tableId.value || tableConfig.value.isRead == 1) return jsonData;
  $form.find(".component").each(function () {
    if (!$(this).parents("tr:first").hasClass("childTr")) {
      //排除子表行控件
      let jsonValue = getComponentData($(this), isValidate);
      if (isValidate && typeof jsonValue === "boolean") {
        jsonData = jsonValue;
        return false;
      }
      if (jsonValue) {
        Object.assign(jsonData, jsonValue);
      }
    }
  });
  if (isValidate && typeof jsonData === "boolean" && !jsonData) {
    return jsonData;
  }
  //查询子表的控件数据
  let childJsonArray = [];
  $form.find("tr.childTr").each(function (i) {
    let childJson = { orderNum: i + 1 };
    if ($(this).attr("id")) {
      childJson.id = $(this).attr("id");
    }
    if ($(this).attr("group_id")) {
      childJson.group_id = $(this).attr("group_id");
    }
    if ($(this).data("id")) {
      Object.assign(childJson, $(this).data("id"));
    }
    if ($(this).data("checkData")) {
      childJson.checkDataList = $(this).data("checkData");
      // Object.assign(childJson, $(this).data("checkData"));
    }
    if (!jsonData.childWrite && $(this).hasClass("child-write")) {
      //child-write：自由填写标识
      jsonData.childWrite = true;
    }
    let $components = $(this).find(".component");
    $components.each(function () {
      let jsonValue = getComponentData($(this), isValidate);
      if (jsonValue) {
        Object.assign(childJson, jsonValue);
      }
      if ($(this).hasClass("addJcxm") && $(this).data("jcxm_id")) {
        const jcxmIds = $(this).data("jcxm_id").split(",");
        jcxmIds.forEach((jcxmId) => {
          childJson[jcxmId] = $(this).attr("name");
        });
      }
    });
    if (!$.isEmptyObject(childJson) && $components.length > 0) {
      //判断json对象是否为空
      childJsonArray.push(childJson);
    }
  });
  if (childJsonArray.length > 0) {
    jsonData.childDataList = childJsonArray;
  }
  jsonData.tFId = tFId.value;

  return jsonData;
}
/**
 * 保存数据
 */
function saveData(isAuto, isValidate) {
  if (!tableId.value || tableConfig.value.isRead == 1) {
    return new Promise((resolve, reject) => {
      resolve();
    });
  }
  let jsonData = getData(isValidate);
  if (isValidate && typeof jsonData === "boolean" && !jsonData) {
    return new Promise((resolve, reject) => {
      reject(false);
    });
  }
  //保存数据
  return addTableData(jsonData).then((res) => {
    if (isAuto) return;
    proxy.$modal.msgSuccess("保存成功！");
  });
}

function submitData(params) {
  proxy.$modal.confirm("确认要提交吗？").then(function () {
    let jsonData = {};
    if (tableId.value) {
      jsonData = getData(true);
    }
    if (typeof jsonData === "boolean" && !jsonData) {
      return;
    }
    if (myId) {
      jsonData.myId = myId;
    }

    if (params) {
      Object.assign(jsonData, params);
    }
    approveData(jsonData).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      bus.emit("dbSave");
      try {
        bus.emit("closeDialog");
      } catch (e) {
        showTable(tFId.value);
      }
    });
  });
}

function returnWrite(isException) {
  proxy.$modal.confirm("确认要退回给填报员吗？").then(function () {
    let jsonData = {};
    if (tableId.value) {
      jsonData = getData();
    }
    if (myId) {
      jsonData.myId = myId;
    }
    if (isException) {
      jsonData.isException = isException;
    }
    returnWriteData(jsonData).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      try {
        bus.emit("closeDialog");
      } catch (e) {
        showTable(tFId.value);
      }
      bus.emit("dbSave");
    });
  });
}
bus.off("returnWrite");
bus.on("returnWrite", (isException) => {
  returnWrite(isException);
});

function showRecord() {
  recordOpen.value = true;
  loadingRecord.value = true;
  userRecordList(tFId.value).then((res) => {
    recordList.value = res.data;
    loadingRecord.value = false;
  });
}

/**
 * 重新加载模板
 */
function handleReloadTable() {
  if (!tableId.value || tableConfig.value.isRead == 1) return;
  if (!tFId.value) {
    proxy.$modal.msgError("未找到表单id！");
    return false;
  }
  proxy.$modal.confirm("确定要重载数据吗？").then(function () {
    reloadTable(tFId.value).then((res) => {
      showTable(res.data);
    });
  });
}
function getComponentData($that, isValidate) {
  let name = $that.attr("name");
  if (!name) return null;
  let json = {};
  let jsonValue = "";
  let $componentName = $that.find("[name=" + name + "]");
  if ($componentName.length == 0) {
    $componentName = $that.find("[data-id='" + name + "']");
  }
  if ($componentName.length == 0) {
    if ($that.hasClass("image")) {
      jsonValue = $that.data("imageid");
    } else if ($that.val().length > 0) {
      jsonValue = $.trim($that.val());
    } else {
      if ($that.data("v-value")) {
        // jsonValue = $.trim($that.data("v-value"));
        jsonValue = proxy.getBackSupAndSub($that.html())
        debugger;
      } else {
        if ($that.data("type")) {
          //长文本
          jsonValue = $.trim($that.html());
        } else {
          jsonValue = $.trim($that.text());
        }
      }
    }
  } else {
    let nodeType = $componentName[0].nodeName;
    let type = $componentName.attr("type");
    if (nodeType && nodeType.toLowerCase() == "select") {
      jsonValue = $componentName.val();
      json[name + "t"] = $componentName.find("option:selected").text();
    } else if (type && (type == "checkbox" || type == "radio")) {
      let $checkbox = $that.find("input[data-id='" + name + "']:checked");
      if ($checkbox.length == 0) return null;
      let values = "";
      let texts = "";
      $checkbox.each(function () {
        values += "," + this.value;
        texts += "`" + $(this).next().text();
      });
      jsonValue = values.substring(1);
      json[name + "t"] = texts.substring(1);
    } else if ($componentName.hasClass("sign")) {
      //签字控件并且显示
      if ($componentName.is(":visible")) {
        jsonValue = $componentName.attr("src");
      } else if (isValidate) {
        proxy.$modal.msgError($componentName.attr("label") + "不能为空！");
        return false;
      }
    } else {
      jsonValue = $.trim($componentName.val());
    }
  }
  //if (jsonValue.length == 0) return null;
  json[name] = jsonValue;
  return json;
}

// ---------------------------------右击列表----------------------------------------
const left = ref(0);
const top = ref(0);
const visible = ref(false);
const contextmenuVal = ref({});
const childComponentList = ref([]);
// 右击事件
function openMenu(e) {
  if (!isWrite) return;
  let $target = $(e.target);
  let isNext = false;
  if (e.target.nodeName.toLowerCase() != "td") {
    $target = $target.parents("td:first");
    isNext = true;
  }
  if (!$target.parents("tr:first").hasClass("childTr")) return;
  if (!isNext && $target.prop("contenteditable") === "false") return;
  // 右击加背景颜色
  var $bgc = $(".greenTdr");
  $bgc.removeClass("greenTdr");
  $target.addClass("greenTdr");
  setPosition(e);
  visible.value = true;

  if (
    e.target.nodeName.toLowerCase() == "td" &&
    e.target.childNodes[0]?.nodeName != "#text" &&
    e.target.childNodes[0]
  ) {
    contextmenuVal.value = e.target.childNodes[0];
    return;
  }

  contextmenuVal.value = e.target;
}
function setPosition(e) {
  const menuWith = 120;
  let position = $(".el-tabs__content").offset();
  const maxWith = $("#dataForm")[0].offsetWidth; // container margin left
  const l = e.clientX - position.left; // 15: margin right
  const maxLeft = maxWith - menuWith; // left boundary

  if (l > maxLeft) {
    left.value = maxLeft;
  } else {
    left.value = l;
  }
  top.value = e.clientY - $(".el-tabs__content")[0].offsetTop + 40;
  left.value = e.clientX;
}

function closeMenu() {
  visible.value = false;
}
// 提示框
const markList = ref([]);
function initPopover() {
  var settings = {
    trigger: "dblclick",
    title: userStepId.value ? "添加标记" : "查看标记",
    width: 300,
    closeable: true,
    // 确定  取消  关闭  按钮显示隐藏
    showBtn: !!userStepId.value,
    style: "",
    padding: false,
    content: function (webuiPopover) {
      var markId = webuiPopover.$element.attr("markId");
      var content = "";
      for (const item of markList.value) {
        if (item.markId == markId) {
          content = item.content;
          break;
        }
      }
      return content;
    },
    onHide: function ($target, $element, btn) {
      return new Promise((resolve, reject) => {
        var markId = $element.attr("markId");
        if (btn == "confirm") {
          var content = $target.find(".webui-popover-content").text();
          var componentId = markId ? "" : $element.attr("name");
          var childFormId = markId ? "" : $element.parent().attr("id");
          if (!content) {
            proxy.$modal.msgError("请输入标记内容");
            return false;
          }
          let temp = {
            content: content,
            componentId: componentId,
            markId: markId,
            childFormId: childFormId,
            tFId: markId ? "" : tFId.value,
          };
          postContent(temp)
            .then((res) => {
              if (!markId) {
                $element.attr("markId", res.data);
                markList.value.push({ markId: res.data, content: content });
              } else {
                for (const item of markList.value) {
                  if (item.markId == markId) {
                    item.content = content;
                    break;
                  }
                }
              }
              $element.addClass("markColor");
              resolve(true);
            })
            .catch(() => {
              reject(false);
            });
        } else {
          if (!markId) {
            proxy.$modal.msgError("没有标记");
            return false;
          }
          delContent(markId)
            .then((res) => {
              proxy.$modal.msgSuccess("删除成功");
              markList.value = markList.value.filter((item) => {
                return item.markId != markId;
              });
              $element.removeAttr("markId");
              $element.removeClass("markColor");
              resolve(true);
            })
            .catch((res) => {
              reject(false);
            });
        }
      });
    },
  };
  if (userStatus.value === 0) {
    let markParams = {};
    if (isWrite) {
      //填报环节可以查看所有标记
      markParams.myId = myId;
    } else {
      //当前是添加标记环节，只能查看自己的标记。
      markParams.tFId = tFId.value;
    }
    getMarkList(markParams).then((res) => {
      markList.value = res.data;
      for (const item of markList.value) {
        let $component;
        if (item.childFormId) {
          //子表行
          $component = $("#" + item.childFormId).find(
            "[name='" + item.componentId + "']"
          );
        } else {
          $component = $("[name='" + item.componentId + "']");
        }
        if ($component.length > 0) {
          $component.addClass("markColor").addClass("mark_");
          $component.attr("markId", item.markId);
        }
      }
      if (markList.value.length > 0 || userStepId.value == 1 || userStepId.value == 2) {
        $(".mark_").webuiPopover("destroy").webuiPopover(settings);
      }
    });
  }
}

// 向下填充
function downWrite(target) {
  let $s = $(target);
  let isChild = target.nodeName.toLowerCase() != "td";
  if (isChild) {
    let value = $s.val();
    let $target = $s.parents("td:first");
    var $tr = $target.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      var $t = $tr.find("[name='" + $target.attr("name") + "']");
      if ($t.length == 0) {
        break;
      }
      if ($t[1].type == "select-one") {
        var $options = $t[1].children;
        for (const index in $options) {
          if ($options[index].getAttribute("value") == value) {
            $options[index].setAttribute("selected", "");
            break;
          } else {
            $options[index].removeAttribute("selected");
          }
        }
      } else {
        var $e = $t[1];
        $e.value = value;
      }
    }
  } else {
    let value = $s.text();
    var $tr = $s.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      let $td = $tr.find("[name='" + $s.attr("name") + "']");
      if ($td.length == 0) {
        break;
      }
      $td.text(value);
    }
  }
}

// 根据条件向下填充
function byConditionDownWrite(target, cId) {
  let $s = $(target);
  let isChild = target.nodeName.toLowerCase() != "td";
  var clickValue = "";
  if (isChild) {
    for (const item of $s.parents("td:first").siblings()) {
      if (item.attributes.name.value == cId) {
        let $i = $(item);
        clickValue = $i.text();
        break;
      }
    }
    let value = $s.val();
    let $target = $s.parents("td:first");
    var $tr = $target.parents("tr:first");
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      var $t = $tr.find("[name='" + $target.attr("name") + "']");
      if ($t.length == 0) {
        break;
      }
      if ($t[1].type == "select-one") {
        var $options = $t[1].children;
        for (const item of $tr[0].children) {
          if (item.attributes.name.value == cId) {
            let $i = $(item);
            if ($i.text() == clickValue) {
              for (const index in $options) {
                if ($options[index].getAttribute("value") == value) {
                  $options[index].setAttribute("selected", "");
                  break;
                } else {
                  $options[index].removeAttribute("selected");
                }
              }
            }
            break;
          }
        }
      } else {
        for (const item of $tr[0].children) {
          if (item.attributes.name.value == cId) {
            let $i = $(item);
            if ($i.text() == clickValue) {
              var $e = $t[1];
              $e.value = value;
            }
            break;
          }
        }
      }
    }
  } else {
    let value = $s.text();
    var $tr = $s.parents("tr:first");
    for (const item of $s.siblings()) {
      if (item.attributes.name.value == cId) {
        let $i = $(item);
        clickValue = $i.text();
        break;
      }
    }
    while (true) {
      $tr = $tr.next();
      if ($tr.length == 0) {
        break;
      }
      let $td = $tr.find("[name='" + $s.attr("name") + "']");
      if ($td.length == 0) {
        break;
      }
      for (const item of $tr[0].children) {
        if (item.attributes.name.value == cId) {
          let $i = $(item);
          if ($i.text() == clickValue) {
            $td.text(value);
          }
          break;
        }
      }
    }
  }
}

// 增加行
function addTr(target) {
  var $target = $(target);
  var $tr = $target.parents("tr:first");
  let $clone = $tr.clone();
  $tr.after($clone);
  cursorStyle.value = "pointer";
}

const cursorStyle = ref("pointer");

// 删除行
function delTr(target) {
  if ($("tr.childTr").length == 1) {
    return;
  }
  var $target = $(target);
  var $tr = $target.parents("tr:first");
  $tr.remove();
  if ($("tr.childTr").length == 1) {
    cursorStyle.value = "not-allowed";
  } else {
    cursorStyle.value = "pointer";
  }
}

// 显示隐藏ul中的li
function showDown(e) {
  let $target = $(e);
  if (e.nodeName?.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  if (!$target.attr("sourcetype")) return false;
  let sourcetype = parseInt($target.attr("sourcetype"));
  let isWrite = parseInt($target.attr("isWrite"));
  if (sourcetype != 2 && sourcetype != 3 && isWrite != 1) return false;
  return true;
}

// 显示隐藏ul中的li
function showTr(e) {
  let $target = $(e);
  if (e.nodeName?.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  if (!$target.parents("tr:first").is(".child-write")) return false;
  return true;
}

// 单击td变色
function tdColor(e) {
  var $target = $(e.target);
  var $bgc = $(".greenTdr");
  $bgc.removeClass("greenTdr");
  if ($target[0].tagName.toLowerCase() != "td") {
    $target = $target.parents("td:first");
  }
  $target.addClass("greenTdr");
}

// 双击tr变色
function trColor(e) {
  var $target = $(e.target);
  var $tr = $target.parents("tr:first");
  var $bgc = $(".greenTdr");
  $bgc.removeClass("greenTdr");
  $tr.addClass("greenTdr");
}

watch(visible, (value) => {
  if (value) {
    document.body.addEventListener("click", closeMenu);
  } else {
    document.body.removeEventListener("click", closeMenu);
  }
});

// -------------------------------------------打印---------------------------------------------
function printDateForm() {
  let isPortrait = $("#dataForm").find("table:first").width() * 0.75 > 600;
  $("#dataForm").jqprint({
    debug: false,
    importCSS: false,
    operaSupport: true,
    printContainer: true,
    portrait: isPortrait,
  });
}

//打印表单
bus.off("printDateForm");
bus.on("printDateForm", () => {
  printDateForm();
});

bus.off("relJzDataList");
bus.on("relJzDataList", (data) => {
  clearTip();
  const { modelType, relDataList } = data;
  if (modelType == 6) {
    //1760269487982305281:校准分析表的检测值。
    const targetComponentId = "1760269487982305281";
    for (let i in relDataList) {
      const relData = relDataList[i];
      const sJIds = relData.sJId.split(",");
      for (let sJId of sJIds) {
        const $tr = $form.find("tr[data-sjid='" + sJId + "']");
        if ($tr.length == 0) continue;
        const $targetComponent = $tr.find("td[name='" + targetComponentId + "']");
        $targetComponent.html(relData.value ? relData.value : "");
        $targetComponent.addClass("tipInfo");
      }
    }
  } else if (modelType == 23) {
    //穿透表
    const prevComId = "1790741161131241474"; //前管值控件
    const afterComId = "1790741259483475969"; //后管值控件
    for (let i in relDataList) {
      const relData = relDataList[i];
      const sJIds = relData.sJId.split(",");
      for (let sJId of sJIds) {
        const $tr = $form.find("tr[data-sjid='" + sJId + "']");
        if ($tr.length > 0) {
          const $targetComponent = $tr.find("td[name='" + prevComId + "']");
          $targetComponent.html(relData.value ? relData.value : "");
          $targetComponent.addClass("tipInfo");
        } else {
          $form.find("tr.childTr").each(function () {
            const hiddenJson = $(this).data("id");
            for (const key in hiddenJson) {
              if (hiddenJson[key] == sJId) {
                const $targetComponent = $(this).find("td[name='" + afterComId + "']");
                $targetComponent.html(relData.value ? relData.value : "");
                $targetComponent.addClass("tipInfo");
                break;
              }
            }
          });
        }
      }
    }
  }
  clearTip(5000);
});

// ---------------------------------------------回到顶部--------------------------------------
function upClick() {
  document.getElementById("dataForm").scrollIntoView();
}

const textHeight = ref(0);

function getHeight() {
  nextTick(() => {
    if (proxy.$refs["textScrollbarRef"]?.$el) {
      textHeight.value = proxy.getSubFileHeight(proxy, "textScrollbarRef", 75);
    }
  });
}

function clearTip(timeOut) {
  if (!timeOut) {
    $form.find(".tipError").removeClass("tipError");
    $form.find(".tipInfo").removeClass("tipInfo");
    return;
  }
  setTimeout(() => {
    $form.find(".tipError").removeClass("tipError");
    $form.find(".tipInfo").removeClass("tipInfo");
  }, timeOut);
}
function isUpClick() {
  // document.getElementById("dataForm")
}
bus.off("eventResult");
bus.on("eventResult", (data) => {
  debugger;
  if (!isWrite) return;
  if (!tableId.value) return;
  eventResult();
  //计算工作曲线
  try {
    eventLine($form, eventResult);
  } catch (e) {}
  clearTip(5000);
});

function eventResult() {
  if (!isWrite) return;
  if (!tableId.value) return;
  let $childTrs = $form.find("tr.childTr");
  let flagId = 0; //0:初始化值 1：//继续循环 2://停止循环
  let resultMsg = "";
  //设置只提醒一次
  let msgWarningFlag = { flag: false };
  clearTip();
  if ($childTrs.length == 0) {
    for (let formula of formulaList.value) {
      //notResultFormulaList:中间公式
      let notResultFormulaList = formula.notResultFormulaList;
      if (notResultFormulaList && notResultFormulaList.length > 0) {
        for (let notResultFormula of notResultFormulaList) {
          let resultData = handleFormulaResult($form, notResultFormula, msgWarningFlag);
          flagId = resultData.flagId;
          if (flagId == 2) break;
        }
        if (flagId == 2) break;
      }
      let resultData = handleFormulaResult($form, formula, msgWarningFlag);
      flagId = resultData.flagId;
      if (resultData.msgWarning && !msgWarningFlag.flag) {
        if (resultMsg.length > 0) {
          resultMsg += "\n";
        }
        resultMsg += resultData.msgWarning;
      }
      if (flagId == 2) break;
    }
  } else {
    $childTrs.each(function () {
      // if (flagId == 2) {
      //   return false;
      // }
      const sampleType = $(this).attr("sampletype");
      if (sampleType && sampleType == 50) {
        return true;
      }
      flagId = 0;
      let jclbId = $(this).data("jclb-id");
      for (let formula of formulaList.value) {
        //当前公式关联了检测类别
        if (formula.jclbIds) {
          if (jclbId && formula.jclbIds && formula.jclbIds.indexOf(jclbId) == -1) {
            continue;
          }
        }
        // //如果有多个结果公式的情况只需要查询指定的结果公式,isResult:0 结果公式（中间公式不做判断）
        if (
          resultFormula.value &&
          resultFormula.value.formulaId != formula.formulaId &&
          !formula.formulaCondition
        ) {
          if (props.tableConfig.modelType != 23) {//23：穿透表
            continue;
          }
        }
        //notResultFormulaList:中间公式
        let notResultFormulaList = formula.notResultFormulaList;
        if (notResultFormulaList && notResultFormulaList.length > 0) {
          for (let notResultFormula of notResultFormulaList) {
            let resultData = handleFormulaResult(
              $(this),
              notResultFormula,
              msgWarningFlag
            );
            flagId = resultData.flagId;
            if (flagId == 2) break;
          }
          if (flagId == 2) break;
        }
        let resultData = handleFormulaResult($(this), formula, msgWarningFlag);
        if (resultData.msgWarning && !msgWarningFlag.flag) {
          //只需要提示一次。
          if (resultMsg.length > 0) {
            resultMsg += "\n";
          }
          resultMsg += resultData.msgWarning;
          msgWarningFlag.flag = true;
        }
        flagId = resultData.flagId;
        if (flagId == 2) break;
      }
    });
  }
  if (resultMsg.length > 0) {
    proxy.$modal.msgWarning("无法计算结果：" + resultMsg);
  }
  if (tableConfig.value.modelType == 14 && $childTrs.length > 0) {
    eventBzwzIsHg($childTrs);
  }
  eventMergeSampleSumResult($childTrs);
  eventMergeSampleResult($childTrs);
  clearTip(5000);
}
/**
 * 计算合并后的样品结果值。
 */
function eventMergeSampleResult($childTrs) {
  $childTrs.each(function () {
    const $tr = $(this);
    const sampleType = $tr.attr("sampletype");
    if (!sampleType || sampleType != 50) {
      //50:合并的样品
      return true;
    }
    const $resultValues = $tr.find("td.resultValue");
    const sJId = $tr.data("sjid");
    if (!sJId) {
      return true;
    }
    if ($resultValues.length == 0) {
      return false;
    }
    // let splitTrs = $tr.prevAll("tr[sampletype=51]").siblings();
    let $splitTrs = [];
    let $splitTr = $tr.prev();
    while (true) {
      if ($splitTr.length == 0) {
        break;
      }
      if (
        $splitTr.attr("sampletype") != 51 ||
        $splitTr.attr("parentid").indexOf(sJId.split(",")[0]) == -1
      ) {
        $splitTr = $splitTr.prev();
        continue;
      }
      $splitTrs.push($splitTr);
      $splitTr = $splitTr.prev();
    }
    if ($splitTrs.length == 0) {
      proxy.$modal.msgError("未找到拆分的样品");
    }
    $resultValues.each(function () {
      const $resultComponent = $(this);
      $resultComponent.html("");
      const resultName = $resultComponent.attr("name");
      let express = "";
      let firstValue;
      for (let i in $splitTrs) {
        const $splitResult = $splitTrs[i].find("td[name='" + resultName + "']");
        let splitResultValue = getRealValue($splitResult, $splitResult.text());
        if (splitResultValue == -1000 || splitResultValue == -1100) {
          //变量为低于检出限时，结果也为检出限。
          splitResultValue = 0;
        } else if (splitResultValue == -2000) {
          return true;
        } else if (splitResultValue == -3000) {
          $resultComponent.html("/");
          $resultComponent.addClass("tipInfo");
          return true;
        }
        if (!firstValue) {
          firstValue = splitResultValue;
        }
        express += "+" + splitResultValue;
      }
      if (express.length == 0) return true;
      express = express.substring(1);
      express = "(" + express + ")/" + $splitTrs.length;
      const formula = {
        isResult: 1,
        paramList: [{ value: firstValue }],
        ruleList: [{ ruleConditionId: 7, ruleTypeId: 1, xyId: 1 }],
      };
      let resultValue;
      try {
        resultValue = getFormulaResult($resultComponent, formula, express);
      } catch (e) {}
      if (typeof resultValue == "object") {
        resultValue = resultValue["resultValue"];
      }
      $resultComponent.addClass("tipInfo");
      $resultComponent.html(resultValue);
    });
  });
}

/**
 * 计算合并后的样品求和结果值。
 */
function eventMergeSampleSumResult($childTrs) {
  debugger;
  $childTrs.each(function () {
    const $tr = $(this);
    const isSum = $tr.attr("isSum");
    if (!isSum || isSum != 2 || $tr.attr("sampletype") == 50) {
      //2:合并的样品
      return true;
    }
    const $resultValues = $tr.find("td.resultValue");
    if ($resultValues.length == 0) {
      return false;
    }
    const sJId = $tr.data("sjid");
    // let splitTrs = $tr.prevAll("tr[sampletype=51]").siblings();
    let $splitTrs = [];
    $childTrs.each(function () {
      const $childTr = $(this);
      if (
        $childTr.attr("isSum") == 1 &&
        $childTr.attr("parentId") &&
        $childTr.attr("parentId") == sJId
      ) {
        $splitTrs.push($childTr);
      }
    });
    if ($splitTrs.length == 0) {
      proxy.$modal.msgError("未找到需要求和的样品");
    }
    $resultValues.each(function () {
      const $resultComponent = $(this);
      $resultComponent.html("");
      const resultName = $resultComponent.attr("name");
      let express = "";
      let firstValue;
      for (let i in $splitTrs) {
        const $splitResult = $splitTrs[i].find("td[name='" + resultName + "']");
        let splitResultValue = getRealValue($splitResult, $splitResult.text());
        if (splitResultValue == -1000 || splitResultValue == -1100) {
          //变量为低于检出限
          // $resultComponent.html($splitResult.text());
          // $resultComponent.addClass("tipInfo");
          // return true;
          splitResultValue = 0;
        } else if (splitResultValue == -2000) {
          return true;
        } else if (splitResultValue == -3000) {
          $resultComponent.html("/");
          $resultComponent.addClass("tipInfo");
          return true;
        }
        if (!firstValue) {
          firstValue = splitResultValue;
        }
        express += "+" + splitResultValue;
      }
      if (express.length == 0) return true;
      const formula = {
        isResult: 1,
        paramList: [{ value: firstValue }],
        ruleList: [{ ruleConditionId: 7, ruleTypeId: 1, xyId: 1 }],
      };
      let resultValue;
      try {
        resultValue = getFormulaResult($resultComponent, formula, express);
      } catch (e) {}
      if (typeof resultValue == "object") {
        resultValue = resultValue["resultValue"];
      }
      $resultComponent.addClass("tipInfo");
      $resultComponent.html(resultValue);
    });
  });
}
function handleFormulaResult($tr, formula, msgWarningFlag) {
  let resultData = { flagId: 0 }; //0:初始化值 1：//继续循环 2://停止循环
  var $resultComponent = $tr.find("td[name='" + formula.resultId + "']");
  if ($resultComponent.length == 0) {
    $resultComponent = $form.find("td[name='" + formula.resultId + "']");
    if ($resultComponent.length == 0 && !msgWarningFlag.flag) {
      proxy.$modal.msgError(
        "未找到结果控件：" + formula.formulaExpressDisplay.split("=")[0]
      );
      resultData.flagId = 2;
      msgWarningFlag.flag = true;
      return resultData;
    } else {
      if ($resultComponent.length > 1) return {};
      if ($(this).parent().hasClass("childWrite")) return {};
    }
  }
  let resultRowspan = $resultComponent.attr("rowspan");
  //公式条件，不同的条件使用对应的公式，例如:平行样相对偏差和绝对偏差这2个条件的公式就不同。
  let condtion = formula.formulaCondition;
  if (condtion) {
    condtion = condtion.replace("=", "==");
    let conditionId = proxy.getCondtion(condtion);
    const $condition = $form.find("select[name='" + conditionId + "']");
    let conditionValue = $condition.val();
    let conditionText = $condition.find("option:selected").text();
    if (!eval(condtion.replace("φ" + conditionId + "φ", conditionValue)) && !eval(condtion.replace("φ" + conditionId + "φ", "'" + conditionText + "'"))) {
      resultData.flagId = 1;
      return resultData;
    }
  }
  //公式：(φ1696729558972825601φ-φ1696729522671124481φ-φ1697869125480968194φ)/(φ1697869039577427969φ*φ1696045595638382594φ*1000)*100
  //应对的表示：样品浓度=(样品A-空白A0-标曲参数b)/(标曲参数a*取样量*1000)*100
  let express = formula.formulaExpress;
  //公式参数：例如上面的样品A（φ1696729558972825601φ），空白A0（1696729522671124481）等。
  let params = formula.paramList;
  for (let param of params) {
    let paramId = param.componentId;
    // if (paramId == formula.resultId) continue; //当前控件为结果控件。
    let value = "";
    if (param.params && param.params.value) {
      value = param.params.value;
      if (value == "" && !msgWarningFlag.flag) {
        proxy.$modal.msgError("引用参数:" + param.paramName + "不能为空！");
        resultData.flagId = 2;
        msgWarningFlag.flag = true;
        break;
      }
      express = express.replace(eval("/φ" + paramId + "φ/g"), value);
      param.value = value;
      continue;
    }
    let $value = $tr.find("td[name='" + paramId + "']");
    if ($value.length == 0) {
      //读取样品编号1对多行中跨行的数据
      $value = getRowspanValue($form, $tr, paramId);
    }
    if ($value.length == 0 && !msgWarningFlag.flag) {
      proxy.$modal.msgError("未从公式中查找到参数：" + param.paramName);
      resultData.flagId = 2;
      $value.addClass("tipError");
      msgWarningFlag.flag = true;
      break;
    }
    value = getRealValue($resultComponent, $value.text());
    if (value == -1000 || value == -1100) {
      //变量为低于检出限时，结果也为检出限。
      resultData.flagId = 1;
      if (value == -1000) {
        $resultComponent.html($value.text());
      } else {
        $resultComponent.html($resultComponent.data("resultValue"));
      }
      $resultComponent.addClass("tipInfo");
      setIsHg($resultComponent, $value.text());
      break;
    } else if (value == -2000) {
      if ($.trim($value.text()).length == 0 && !msgWarningFlag.flag) {
        proxy.$modal.msgError("公式计算:" + param.paramName + "不能为空！");
        $value.addClass("tipError");
        msgWarningFlag.flag = true;
      } else if (!msgWarningFlag.flag) {
        proxy.$modal.msgError("非法数据：" + param.paramName + "-" + $value.text());
        $value.addClass("tipError");
        msgWarningFlag.flag = true;
      }
      resultData.flagId = 2;
      break;
    } else if (value == -3000) {
      if (formula.formulaExpress.indexOf("last(") == -1) {
        resultData.flagId = 1;
        break;
      }
      value = "";
    } else if (typeof value != "number" && value == "" && !msgWarningFlag.flag) {
      proxy.$modal.msgError("公式计算:" + param.paramName + "不能为空！");
      $value.addClass("tipError");
      msgWarningFlag.flag = true;
      resultData.flagId = 2;
      break;
    }
    express = express.replace(eval("/φ" + paramId + "φ/g"), value);
    param.value = value;
    //求平均值 !$value.attr("rowspan") || $value.attr("rowspan") == 1:意思是当前需要计算平均值的td不能跨行(rowspan)
    if (
      resultRowspan > 1 &&
      params.length == 1 &&
      (!$value.attr("rowspan") || $value.attr("rowspan") == 1)
    ) {
      let $nextTr = $tr.next();
      let count = 1;
      for (let t = 2; t <= resultRowspan; t++) {
        $value = $nextTr.find("td[name='" + paramId + "']");
        value = getRealValue($resultComponent, $value.text());
        if (value == "") {
          continue;
        } else if (value == -1000 || value == -1100) {
          //变量为低于检出限时，结果也为检出限。
          resultData.flagId = 1;
          if (value == -1000) {
            $resultComponent.html($value.text());
          } else {
            $resultComponent.html($resultComponent.data("resultValue"));
          }
          $resultComponent.addClass("tipInfo");
          setIsHg($resultComponent, $value.text());
          break;
        } else if (value == -2000) {
          if ($.trim($value.text()).length == 0 && !msgWarningFlag.flag) {
            proxy.$modal.msgError("公式计算:" + param.paramName + "不能为空！");
            $value.addClass("tipError");
            msgWarningFlag.flag = true;
          } else if (!msgWarningFlag.flag) {
            proxy.$modal.msgError("非法数据：" + param.paramName + "-" + $value.text());
            $value.addClass("tipError");
            msgWarningFlag.flag = true;
          }
          resultData.flagId = 2;
          break;
        } else if (value == -3000) {
          if (formula.formulaExpress.indexOf("last(") == -1) {
            continue;
          } else {
            value = "";
          }
        }
        express += "+" + value;
        count++;
      }
      express = "(" + express + ")/" + count;
    }
  }
  if (resultData.flagId == 1 || resultData.flagId == 2) {
    return resultData;
  }
  let resultValue;
  try {
    resultValue = getFormulaResult($resultComponent, formula, express);
  } catch (e) {
    resultData.msgWarning = e.message;
  }
  if (resultValue == "" && !resultData.msgWarning) {
    resultData.msgWarning = express;
  }

  if (typeof resultValue == "object") {
    resultValue = resultValue["resultValue"];
  }
  $resultComponent.addClass("tipInfo");
  $resultComponent.html(resultValue);
  if ($resultComponent && $resultComponent.data("blur")) {
    //可能有的公式计算的结果做为其它自动计算的变量，例如：标曲表的标曲空白值=当前标曲空白值-第一个空白值。
    $resultComponent.blur();
  }
  setIsHg($resultComponent, resultValue);
  return resultData;
}

bus.off("showInstrumentData");
bus.on("showInstrumentData", function (dataList) {
  if (!dataList || dataList.length == 0) {
    proxy.$modal.msgError("仪器数据读取成功,但未在当前表中找到匹配的样品");
    return;
  }
  var $bgc = $(".tipInfo");
  $bgc.removeClass("tipInfo");
  for (let data of dataList) {
    const $tr = $form.find(`tr[id=${data["-1"]}]`);
    if ($tr.length > 0) {
      for (let key in data) {
        const $td = $tr.find(`td[name=${key}]`);
        if ($td.length > 0) {
          $td.html(data[key]);
          $td.addClass("tipInfo");
        }
      }
    }
  }
  setTimeout(() => {
    var $bgc = $(".tipInfo");
    $bgc.removeClass("tipInfo");
  }, 5000);
  let $data = $form.find("tr.childTr td[name='1698983560917704705']");
  $data.each(function (i) {
    if (i < dataList.length) {
      $(this).text(dataList[i]);
    }
  });
});
bus.off("setResultFormula");
bus.on("setResultFormula", function (getResultFormula) {
  resultFormula.value = getResultFormula[0];
});
bus.off("setHandle");
bus.on("setHandle", function (handleData) {
  Object.assign(tableConfig.value, handleData);
  // handle.value = handleData.handleMc;
  // let jcxmCheckLimitParams = {
  //   tableId: tableId.value,
  //   methodId: methodId.value,
  //   handleMc: handle.value,
  // };
  registerEvent(proxy, $form, tableConfig.value);
});
bus.off("setRelData");
bus.on("setRelData", function (relDataList) {
  out: for (const i in relDataList) {
    const dataMap = relDataList[i];
    let $componentTr = $form.find("tr[id='" + dataMap.id + "']");
    if ($componentTr.length == 0) {
      proxy.$modal.msgError("将数据渲染到当前表中时未找到对应的位置！");
      break;
    }
    for (const compoentId in dataMap) {
      if (compoentId == "id") continue;
      const $dataComponent = $componentTr.find("td[name='" + compoentId + "']");
      if ($dataComponent.length == 0) {
        proxy.$modal.msgError("将数据渲染到当前表中时未找到对应的位置！");
        break out;
      }
      $dataComponent.html(dataMap[compoentId]);
      $dataComponent.addClass("relData"); //给匹配到的数据添加背景色
    }
  }
  proxy.$modal.msgSuccess("数据引用成功！");
  //3秒后自动移除匹配到的数据背景色
  setTimeout(() => {
    $form.find("td.relData").removeClass("relData");
  }, 3000);
});
onMounted(() => {
  nextTick(function () {
    getHeight();
    window.addEventListener("resize", getHeight);
    isUpClick();
    window.addEventListener("resize", isUpClick);
  });
});
onUpdated(() => {
  nextTick(() => {
    getHeight();
    isUpClick();
  });
});
onBeforeUnmount(() => {
  bus.off("submitCallback");
  bus.off("submit" + tFId.value);
  bus.off("submitData" + tFId.value);
  bus.off("handleReloadTable" + tFId.value);
  bus.off("setResultFormula");
  document.removeEventListener("keydown", handleKeyDown);
  window.removeEventListener("resize", getHeight);
  window.addEventListener("resize", isUpClick);
});

// -------------------------------------------手动审核------------------------------------------
const submitOpen = ref(false);
const submitTitle = ref("选择提交人");
const treeData = ref([]);
const defaultProps = ref({ label: "nickName", children: "children" });
const treeLoading = ref(false);
const userId = ref("");
const filterText = ref("");

function submitClose() {
  filterText.value = "";
  userId.value = "";
  treeData.value = [];
}

function Manual() {
  submitOpen.value = true;
  treeLoading.value = true;
  getTreeList().then((res) => {
    treeData.value = proxy.handleTree(res.data, "userId");
    treeLoading.value = false;
    if (nextUser.value.nextUserId) {
      nextTick(() => {
        filterText.value = nextUser.value.nextUserName;
      });
    }
  });
}

function nodeClick(val) {
  userId.value = "";
  if (val.userType == 1) {
    userId.value = val.userId;
  }
}

function submitConfirm(params) {
  if (!userId.value) {
    proxy.$modal.msgError("未选择人员");
    return;
  }
  proxy.$modal.confirm("确定提交吗？").then(function () {
    let jsonData = {};
    if (tableId.value) {
      jsonData = getData(true);
    }
    if (typeof jsonData === "boolean" && !jsonData) {
      return;
    }
    if (myId) {
      jsonData.myId = myId;
    }
    jsonData.userId = userId.value;
    approveData(jsonData).then((res) => {
      proxy.$modal.msgSuccess("提交成功！");
      bus.emit("dbSave");
      try {
        bus.emit("closeDialog");
      } catch (e) {
        showTable(tFId.value);
      }
    });
  });
}

function filterNode(value, data) {
  if (!value) {
    return true; // 如果搜索框为空，则显示所有节点
  }
  return data.nickName.includes(value); // 根据节点的 groupName 属性进行名称过滤
}

watch(
  () => filterText.value,
  (val) => {
    proxy.$refs["treeRef"].filter(val);
  }
);

defineExpose({
  showTable,
});

function upCommon(tr, td) {
  var foundEditableTd = false;
  var currentTr = tr;

  if (currentTr && !foundEditableTd) {
    var tds = currentTr.querySelectorAll("td");
    for (var i = tds.length - 1; i >= 0; i--) {
      var currentTd = tds[i];
      if (currentTd.getAttribute("contentEditable") == "true") {
        currentTd.focus();
        var $bgc = $(".greenTdr");
        $bgc.removeClass("greenTdr");
        currentTd.classList.add("greenTdr");
        foundEditableTd = true;
        break;
      }
    }
    if (!foundEditableTd) {
      ArrowUp({ target: td ? td : tds[tds.length - 1] });
    }
  }
}

function downCommon(tr, td) {
  var foundEditableTd = false;
  var currentTr = tr;
  if (currentTr && !foundEditableTd) {
    var tds = currentTr.querySelectorAll("td");
    for (var i = 0; i < tds.length; i++) {
      var currentTd = tds[i];
      if (currentTd.getAttribute("contentEditable") == "true") {
        currentTd.focus();
        var $bgc = $(".greenTdr");
        $bgc.removeClass("greenTdr");
        currentTd.classList.add("greenTdr");
        foundEditableTd = true;
        break;
      }
    }
    if (!foundEditableTd) {
      ArrowDown({ target: td ? td : tds[0] });
    }
  }
}

function focusTd(td) {
  td.focus();
  var $bgc = $(".greenTdr");
  $bgc.removeClass("greenTdr");
  td.classList.add("greenTdr");
}

function ArrowUp(e) {
  var tdIndex = Array.from(e.target.parentNode.children).indexOf(e.target);
  var tr = e.target.closest("tr");
  if (tr) {
    var previousTr = tr.previousElementSibling;
    if (previousTr) {
      var td = previousTr.querySelectorAll("td")[tdIndex];
      if (td) {
        if (td.getAttribute("contentEditable") == "true") {
          focusTd(td);
        } else {
          upCommon(previousTr, td);
        }
      } else {
        upCommon(previousTr);
      }
    } else {
      var table = tr.closest("table");
      if (table) {
        var previousTable = table.previousElementSibling;
        if (previousTable) {
          var lastRow = previousTable.querySelector("tbody tr:last-child");
          if (lastRow) {
            var td = lastRow.querySelectorAll("td")[tdIndex];
            if (td) {
              if (td.getAttribute("contentEditable") == "true") {
                focusTd(td);
              } else {
                upCommon(lastRow, td);
              }
            } else {
              upCommon(lastRow);
            }
          }
        }
      }
    }
  }
}

function ArrowDown(e) {
  var tdIndex = Array.from(e.target.parentNode.children).indexOf(e.target);
  var tr = e.target.closest("tr");
  if (tr) {
    var previousTr = tr.nextElementSibling;
    if (previousTr) {
      var td = previousTr.querySelectorAll("td")[tdIndex];
      if (td) {
        if (td.getAttribute("contentEditable") == "true") {
          focusTd(td);
        } else {
          downCommon(previousTr, td);
        }
      } else {
        downCommon(previousTr);
      }
    } else {
      var table = tr.closest("table");
      if (table) {
        var nextTable = table.nextElementSibling;
        if (nextTable) {
          var lastRow = nextTable.querySelector("tbody tr:first-child");
          if (lastRow) {
            var td = lastRow.querySelectorAll("td")[tdIndex];
            if (td) {
              if (td.getAttribute("contentEditable") == "true") {
                focusTd(td);
              } else {
                downCommon(lastRow, td);
              }
            } else {
              downCommon(lastRow);
            }
          }
        }
      }
    }
  }
}

function ArrowLeft(e) {
  var previousTD = e.target.previousElementSibling;
  if (previousTD) {
    if (previousTD.getAttribute("contentEditable") == "true") {
      focusTd(previousTD);
    } else {
      ArrowLeft({ target: previousTD });
    }
  } else {
    var previousTr = e.target.closest("tr").previousElementSibling;
    if (previousTr) {
      var tds = previousTr.querySelectorAll("td");
      var td = tds[tds.length - 1];
      if (td.getAttribute("contentEditable") == "true") {
        focusTd(td);
      } else {
        ArrowLeft({ target: td });
      }
    } else {
      var previousTable = e.target.closest("tr").closest("table").previousElementSibling;
      if (previousTable) {
        var lastRow = previousTable.querySelector("tbody tr:last-child");
        if (lastRow) {
          var tds = lastRow.querySelectorAll("td");
          var td = tds[tds.length - 1];
          if (td.getAttribute("contentEditable") == "true") {
            focusTd(td);
          } else {
            ArrowLeft({ target: td });
          }
        }
      }
    }
  }
}

function ArrowRight(e) {
  var nextTD = e.target.nextElementSibling;
  if (nextTD) {
    if (nextTD.getAttribute("contentEditable") == "true") {
      focusTd(nextTD);
    } else {
      ArrowRight({ target: nextTD });
    }
  } else {
    var previousTr = e.target.closest("tr").nextElementSibling;
    if (previousTr) {
      var tds = previousTr.querySelectorAll("td");
      var td = tds[0];
      if (td.getAttribute("contentEditable") == "true") {
        focusTd(td);
      } else {
        ArrowRight({ target: td });
      }
    } else {
      var nextTable = e.target.closest("tr").closest("table").nextElementSibling;
      if (nextTable) {
        var firstRow = nextTable.querySelector("tbody tr:first-child");
        if (firstRow) {
          var tds = firstRow.querySelectorAll("td");
          var td = tds[0];
          if (td.getAttribute("contentEditable") == "true") {
            focusTd(td);
          } else {
            ArrowRight({ target: td });
          }
        }
      }
    }
  }
}

// 定义事件处理函数
function handleKeyDown(e) {
  if (e.key) {
    var dataForm = document.getElementById("dataForm");
    var event = e.target;
    if (dataForm.contains(event)) {
      if (e.key == "ArrowUp") {
        ArrowUp({ target: event });
      } else if (e.key == "ArrowDown") {
        ArrowDown({ target: event });
      } else if (e.key == "ArrowLeft") {
        ArrowLeft({ target: event });
      } else if (e.key == "ArrowRight") {
        ArrowRight({ target: event });
      }
    }
  }
}

bus.off("copyLast");
bus.on("copyLast", function (data) {
  if (!data) return;
  var $bgc = $(".tipInfo");
  $bgc.removeClass("tipInfo");
  const $dataForm = $("#dataForm");
  for (let key in data) {
    if (key == "1696048841341812737") continue; //排除检出限
    const $td = $dataForm.find(`td[name=${key}]`);
    const $select = $td.find("select");
    if ($select.length > 0) {
      // 如果td下存在select元素，则修改select的值
      $select.find('option[value="' + data[key] + '"]').prop("selected", true);
      $td.addClass("tipInfo");
    } else {
      // 否则修改td的内容
      if ($td.parents("tr:first").hasClass("childTr")) {
        continue;
      }
      if ($td.length > 0) {
        $td.html(data[key]);
        $td.addClass("tipInfo");
      }
    }
  }
  proxy.$modal.msgSuccess("复制成功");
  setTimeout(() => {
    var $bgc = $(".tipInfo");
    $bgc.removeClass("tipInfo");
  }, 5000);
});

// 添加事件监听器
document.addEventListener("keydown", handleKeyDown);
</script>

<style lang="scss" scoped>
#dataForm:deep(div.sign:hover .cha) {
  display: block !important;
}

#dataForm:deep(td) {
  word-break: break-all !important;
  font-size: 14px;
  vertical-align: middle;
}

#dataForm:deep(.greenTdr) {
  background-color: #d8fdde;
}

#dataForm:deep(.tipInfo) {
  color: green !important;
}

#dataForm:deep(.tipError) {
  border: solid 2px red !important;
}

#dataForm:deep(.fixed-head),
#dataForm:deep(.fixed-foot) {
  position: sticky;
  background-color: #eee;
  z-index: 1;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;

    &:hover {
      background: #eee;
    }
  }
}

#dataForm:deep(.markColor) {
  background: transparent url("/src/assets/images/report.gif") no-repeat scroll 0 0;
}

#dataForm:deep(.relData) {
  background: #e6a23c;
}

/** 解决手动选择人员框时 el-scrollbar遮挡footer中的按钮导致无法点击*/
.dialogUser .el-scrollbar {
  height: 90%;
}
</style>
